// 弹幕
const express = require('express');
const query = require('../utils/query');
const {check} = require('../utils/valitate');
const {createUpload} = require('../utils/file');

const router = express.Router();
const upload = createUpload('public/upload/comment');

// 发表评论
router.post(
    '/',
    upload.single('img'),
    check([], ['video_id', 'content']),  // 参数校验
    async (req, res) => {
        try {
            const {video_id, content} = req.body; // 视频id和内容
            const user_id = req.userInfoLaoGuo.Id;  // 用户id
            const img = req.file?.path || '';
            // 执行保存操作
            await query(
                "INSERT INTO comment (video_id,user_id,content,img) values (?,?,?,?)",
                [video_id, user_id, content, img]
            );
            res.send({
                code: 1,
                msg: '发表成功'
            });
        } catch (error) {
            console.log(error);
            res.send({
                code: 0,
                msg: '发布失败'
            })
        }
    }
)
// 获取评论
router.get(
    '/',
    check(['id'], []),
    async function (req, res) {
        const sql = `
        SELECT 
            c.id,c.content,c.time,c.img,u.avatar,u.user_name
        FROM 
            comment as c 
        LEFT JOIN
            user as u
        ON 
            u.id=c.user_id
        WHERE 
            c.video_id=?
        ORDER BY c.time desc`;
        const data = await query(sql,[req.query.id]);
        res.send({
            code: 1,
            msg: '查询成功',
            data
        });
    }
);

module.exports = router;
